const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 搜索用户
router.get('/search/users', (req, res) => {
  const { q } = req.query;
  const searchTerm = `%${q}%`;

  db.query(
    'SELECT id, username, avatar FROM users WHERE username LIKE ? OR email LIKE ?',
    [searchTerm, searchTerm],
    (error, results) => {
      if (error) {
        return res.status(500).json({ error: error.message });
      }
      res.json(results);
    }
  );
});

// 搜索帖子
router.get('/search/posts', (req, res) => {
  const { q } = req.query;
  const searchTerm = `%${q}%`;

  db.query(`
    SELECT p.*, u.username, 
           (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count
    FROM posts p
    JOIN users u ON p.user_id = u.id
    WHERE p.title LIKE ? OR p.content LIKE ?
    ORDER BY p.created_at DESC
  `, [searchTerm, searchTerm],
    (error, results) => {
      if (error) {
        return res.status(500).json({ error: error.message });
      }
      res.json(results);
    }
  );
});

module.exports = router; 